import 'package:flutter/foundation.dart';
import 'package:meco/common/models/chat_message_model.dart';
import 'package:meco/common/data/services/database_service.dart';
import 'package:meco/common/data/repositories/chat_room_repository.dart';

class ChatMessageRepository {
  final DatabaseService _databaseService = DatabaseService();
  final ChatRoomRepository _chatRoomRepository = ChatRoomRepository();
  final String _tableName = 'chat_messages';

  // 发送消息
  Future<int> sendMessage(ChatMessage message) async {
    final db = await _databaseService.database;
    try {
      // 1. 保存消息
      final messageId = await db.insert(_tableName, message.toJson());

      // 2. 更新聊天室最后消息信息
      final success = await _chatRoomRepository.updateLastMessage(
        message.chatRoomId,
        message.content,
        message.createdAt,
      );

      debugPrint('更新聊天室最后消息${success ? '成功' : '失败'}: ${message.content}');

      return messageId;
    } catch (e) {
      debugPrint('发送消息失败: $e');
      return -1;
    }
  }

  // 获取消息详情
  Future<ChatMessage?> getMessageById(int id) async {
    final db = await _databaseService.database;
    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'id = ?',
        whereArgs: [id],
      );

      if (maps.isEmpty) {
        return null;
      }

      return ChatMessage.fromJson(maps.first);
    } catch (e) {
      debugPrint('获取消息详情失败: $e');
      return null;
    }
  }

  // 更新消息
  Future<bool> updateMessage(ChatMessage message) async {
    if (message.id == null) {
      return false;
    }

    final db = await _databaseService.database;
    try {
      final result = await db.update(
        _tableName,
        message.toJson(),
        where: 'id = ?',
        whereArgs: [message.id],
      );
      return result > 0;
    } catch (e) {
      debugPrint('更新消息失败: $e');
      return false;
    }
  }

  // 删除消息
  Future<bool> deleteMessage(int id) async {
    final db = await _databaseService.database;
    try {
      final result = await db.delete(
        _tableName,
        where: 'id = ?',
        whereArgs: [id],
      );
      return result > 0;
    } catch (e) {
      debugPrint('删除消息失败: $e');
      return false;
    }
  }

  // 获取聊天室的消息列表
  Future<List<ChatMessage>> getMessagesByChatRoomId(
    int chatRoomId, {
    int limit = 50,
    int offset = 0,
  }) async {
    final db = await _databaseService.database;
    try {
      final List<Map<String, dynamic>> maps = await db.query(
        _tableName,
        where: 'chat_room_id = ?',
        whereArgs: [chatRoomId],
        orderBy: 'created_at DESC',
        limit: limit,
        offset: offset,
      );

      if (maps.isEmpty) {
        return [];
      }

      return maps.map((map) => ChatMessage.fromJson(map)).toList();
    } catch (e) {
      debugPrint('获取聊天室消息失败: $e');
      return [];
    }
  }

  // 标记消息为已读
  Future<bool> markMessageAsRead(int messageId, int userId) async {
    final db = await _databaseService.database;
    try {
      // 1. 获取消息
      final message = await getMessageById(messageId);
      if (message == null) return false;

      // 2. 标记为已读
      final updatedMessage = message.markAsRead(userId);

      // 3. 更新到数据库
      final result = await db.update(
        _tableName,
        {'read_by': updatedMessage.readBy},
        where: 'id = ?',
        whereArgs: [messageId],
      );
      return result > 0;
    } catch (e) {
      debugPrint('标记消息已读失败: $e');
      return false;
    }
  }

  // 批量标记聊天室消息为已读
  Future<bool> markAllMessagesAsRead(int chatRoomId, int userId) async {
    final db = await _databaseService.database;
    try {
      // 1. 获取该聊天室所有未读的消息
      final List<Map<String, dynamic>> messages = await db.query(
        _tableName,
        where: 'chat_room_id = ? AND sender_id != ?',
        whereArgs: [chatRoomId, userId],
      );

      // 2. 遍历每条消息并标记为已读
      for (var messageMap in messages) {
        final message = ChatMessage.fromJson(messageMap);
        if (!message.isReadBy(userId)) {
          await markMessageAsRead(message.id!, userId);
        }
      }

      return true;
    } catch (e) {
      debugPrint('批量标记消息已读失败: $e');
      return false;
    }
  }
}
